package edu.nf.project.services.task;

import edu.nf.project.entitys.entity.storeOperation.convention.inspect.SelfInspection;
import edu.nf.project.services.storeOperation.SelfInspectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;

/**
 * @author CSY
 * @date 2025 - 06 - 16
 * 自检任务类
 */
@Component
public class SelfInspectionTask {
    @Autowired
    private SelfInspectionService selfInspectionService;

    /**
     * 每天8点创建记录
     */
    @Scheduled(cron = "0 0 8 * * ?")
    public void createDailyRecord(){
        executeTask();
    }

    /**
     * 应用启动时检查是否需要创建记录
     */
    public void checkAndExecute(){
        //获取当前时间
        Calendar now = Calendar.getInstance();
        //获取时间并设置时间
        Calendar targetTime = Calendar.getInstance();
        //设置小时
        targetTime.set(Calendar.HOUR_OF_DAY, 8);
        //分钟
        targetTime.set(Calendar.MINUTE, 0);
        //秒
        targetTime.set(Calendar.SECOND, 0);
        //毫秒
        targetTime.set(Calendar.MILLISECOND, 0);

        //判断当前时间是否操作8点并且数据库不存在今天的数据
        if (now.after(targetTime)&&!isRecordExistsToday()){
            //调用添加数据的方法
            executeTask();
        }
    }

    /**
     * 创建未上传的自检记录
     */
    public void executeTask(){
        //如果为空那么进行创建记录
        if (!isRecordExistsToday()){
            SelfInspection selfInspection = new SelfInspection();
            selfInspection.setSiDate(getTime());
            selfInspection.setSiStatus(false);
            selfInspection.setStoreId(4);

            selfInspectionService.createSelfInspection(selfInspection);
        }
    }

    /**
     * 判断是否存在今天的记录
     * @return
     */
    private boolean isRecordExistsToday(){
        return selfInspectionService.existsByDate(getTime());
    }

    private Date getTime(){
        //初始化Calendar对象自定义时间
        Calendar now = Calendar.getInstance();
        //设置年月日时分秒毫秒
        int year = now.get(Calendar.YEAR);
        int month = now.get(Calendar.MONTH);
        int day = now.get(Calendar.DAY_OF_MONTH);
        now.set(year,month,day,8,0,0);
        now.set(Calendar.MILLISECOND, 0);
        return now.getTime();
    }

}
